import React, { useState } from 'react';
import { ChevronDown, ChevronRight, Database, GitBranch, Target, FileText, Award, BarChart3 } from 'lucide-react';

export default function ESGBusinessScenarios() {
  const [expandedScenario, setExpandedScenario] = useState('pcf');

  const scenarios = [
    {
      id: 'pcf',
      title: '产品碳足迹 (PCF)',
      icon: <BarChart3 className="w-6 h-6" />,
      color: '#1976d2',
      bgColor: '#e3f2fd',
      description: '计算产品全生命周期的碳排放量',
      standards: ['ISO 14067', 'GHG Protocol Product Standard', 'PAS 2050'],
      coreModels: ['Product', 'Activity', 'Material', 'GHGEmissionsResult', 'EmissionFactor'],
      dataFlow: [
        { step: 1, action: '定义产品边界', models: ['Product'], description: '设定功能单位、系统边界、生命周期阶段' },
        { step: 2, action: '收集活动数据', models: ['Activity', 'Material', 'Supplier'], description: '原材料、生产、运输、使用、废弃处理数据' },
        { step: 3, action: '匹配排放因子', models: ['EmissionFactor'], description: '根据地理位置、时间、活动类型匹配因子' },
        { step: 4, action: '计算碳足迹', models: ['GHGEmissionsResult'], description: '按生命周期阶段计算CO2当量' },
        { step: 5, action: '生成PCF报告', models: ['ReportTemplateDefinition', 'FileInfo'], description: '输出符合标准的碳足迹报告' }
      ],
      keyQueries: [
        'SELECT p.product_name, SUM(g.total_co2_equivalent) as total_pcf FROM Product p JOIN GHGEmissionsResult g ON p.product_id = g.product_id GROUP BY p.product_id',
        'SELECT lifecycle_stage, SUM(total_co2_equivalent) as stage_emissions FROM GHGEmissionsResult WHERE calculation_type = "PCF" GROUP BY lifecycle_stage'
      ]
    },
    {
      id: 'inventory',
      title: '组织碳盘查',
      icon: <Database className="w-6 h-6" />,
      color: '#388e3c',
      bgColor: '#e8f5e8',
      description: '计算组织范围内的温室气体排放清单',
      standards: ['GHG Protocol Corporate Standard', 'ISO 14064-1', '国家发改委企业温室气体核算指南'],
      coreModels: ['Organization', 'OperationalEntity', 'Activity', 'GHGEmissionsResult', 'ESGProject'],
      dataFlow: [
        { step: 1, action: '确定组织边界', models: ['Organization', 'OperationalEntity'], description: '设定股权份额或运营控制边界' },
        { step: 2, action: '识别排放源', models: ['Activity'], description: '按Scope1/2/3分类识别所有排放源' },
        { step: 3, action: '收集活动数据', models: ['Activity'], description: '燃料消耗、电力使用、工艺过程等数据' },
        { step: 4, action: '计算排放量', models: ['GHGEmissionsResult', 'EmissionFactor'], description: '按范围分别计算CO2当量' },
        { step: 5, action: '编制清单报告', models: ['ComplianceRecord', 'ReportTemplateDefinition'], description: '生成符合标准的盘查报告' }
      ],
      keyQueries: [
        'SELECT scope_type, SUM(total_co2_equivalent) as scope_emissions FROM GHGEmissionsResult WHERE calculation_type = "INVENTORY" GROUP BY scope_type',
        'SELECT e.entity_name, SUM(g.total_co2_equivalent) as entity_emissions FROM OperationalEntity e JOIN Activity a ON e.entity_id = a.entity_id JOIN GHGEmissionsResult g ON a.activity_id = g.activity_id GROUP BY e.entity_id'
      ]
    },
    {
      id: 'cbam',
      title: 'CBAM合规',
      icon: <FileText className="w-6 h-6" />,
      color: '#d32f2f',
      bgColor: '#ffebee',
      description: '欧盟碳边境调节机制合规报告',
      standards: ['EU CBAM Regulation', 'EU Commission Implementing Regulation'],
      coreModels: ['Product', 'GHGEmissionsResult', 'ComplianceRecord', 'RegulationStandardInitiative'],
      dataFlow: [
        { step: 1, action: '识别CBAM产品', models: ['Product'], description: '根据HS编码识别覆盖产品' },
        { step: 2, action: '计算隐含碳排放', models: ['GHGEmissionsResult'], description: '计算产品生产过程的直接和间接排放' },
        { step: 3, action: '确定碳价格', models: ['CarbonAsset'], description: '计算原产国实际碳价格' },
        { step: 4, action: '申报CBAM证书', models: ['ComplianceRecord'], description: '提交季度排放数据和证书申请' },
        { step: 5, action: '跟踪合规状态', models: ['ComplianceRecord'], description: '监控证书状态和合规截止日期' }
      ],
      keyQueries: [
        'SELECT p.hs_code, SUM(g.total_co2_equivalent) as cbam_emissions FROM Product p JOIN GHGEmissionsResult g ON p.product_id = g.product_id WHERE g.calculation_type = "CBAM" GROUP BY p.hs_code',
        'SELECT compliance_status, COUNT(*) as count FROM ComplianceRecord WHERE compliance_type = "CBAM_CERTIFICATE" GROUP BY compliance_status'
      ]
    },
    {
      id: 'cdp',
      title: 'CDP评估',
      icon: <Award className="w-6 h-6" />,
      color: '#7b1fa2',
      bgColor: '#f3e5f5',
      description: 'CDP气候变化问卷评估',
      standards: ['CDP Climate Change Questionnaire', 'CDP Scoring Methodology'],
      coreModels: ['Organization', 'GHGEmissionsResult', 'ESGGoal', 'ActionPlan', 'RatingIndicatorDefinition'],
      dataFlow: [
        { step: 1, action: '收集治理信息', models: ['Organization', 'ActionPlan'], description: '气候治理结构、风险管理流程' },
        { step: 2, action: '披露排放数据', models: ['GHGEmissionsResult'], description: 'Scope1/2/3排放量和强度指标' },
        { step: 3, action: '设定减排目标', models: ['ESGGoal'], description: 'SBTi目标、净零承诺等' },
        { step: 4, action: '评估指标得分', models: ['RatingIndicatorDefinition'], description: '按CDP评分方法计算各指标得分' },
        { step: 5, action: '生成CDP报告', models: ['ComplianceRecord', 'FileInfo'], description: '提交CDP平台和生成评估报告' }
      ],
      keyQueries: [
        'SELECT indicator_category, AVG(score) as avg_score FROM CDPAssessment WHERE rating_system = "CDP" GROUP BY indicator_category',
        'SELECT goal_type, COUNT(*) as goal_count FROM ESGGoal WHERE goal_type LIKE "%SBTi%" OR goal_type LIKE "%NetZero%" GROUP BY goal_type'
      ]
    },
    {
      id: 'ecovadis',
      title: 'EcoVadis认证',
      icon: <Target className="w-6 h-6" />,
      color: '#f57c00',
      bgColor: '#fff3e0',
      description: 'EcoVadis可持续发展评估',
      standards: ['EcoVadis Assessment Methodology', 'CSR Risk Assessment'],
      coreModels: ['Organization', 'Supplier', 'ActionPlan', 'RatingIndicatorDefinition', 'ComplianceRecord'],
      dataFlow: [
        { step: 1, action: '环境管理评估', models: ['Organization', 'GHGEmissionsResult'], description: '环境政策、生命周期分析、环境行动计划' },
        { step: 2, action: '劳工人权评估', models: ['Organization', 'ActionPlan'], description: '员工权利、工作条件、职业健康安全' },
        { step: 3, action: '商业道德评估', models: ['Organization'], description: '反腐败、反竞争、信息透明度' },
        { step: 4, action: '可持续采购评估', models: ['Supplier'], description: '供应商ESG管理、供应链风险控制' },
        { step: 5, action: '综合评分认证', models: ['ComplianceRecord', 'RatingIndicatorDefinition'], description: '获得EcoVadis徽章和评分' }
      ],
      keyQueries: [
        'SELECT s.esg_rating_ecovadis, COUNT(*) as supplier_count FROM Supplier s GROUP BY s.esg_rating_ecovadis',
        'SELECT theme, weighted_score FROM EcoVadisAssessment WHERE assessment_year = YEAR(CURDATE()) ORDER BY weighted_score DESC'
      ]
    },
    {
      id: 'esg_report',
      title: 'ESG综合报告',
      icon: <GitBranch className="w-6 h-6" />,
      color: '#00695c',
      bgColor: '#e0f2f1',
      description: '年度ESG可持续发展报告',
      standards: ['GRI Standards', 'SASB Standards', 'ISSB Standards', 'TCFD Recommendations'],
      coreModels: ['Organization', 'ESGMetricDefinition', 'ESGGoal', 'ActionPlan', 'ReportTemplateDefinition'],
      dataFlow: [
        { step: 1, action: '确定报告框架', models: ['ReportTemplateDefinition'], description: '选择GRI、SASB等报告标准' },
        { step: 2, action: '收集ESG指标', models: ['ESGMetricDefinition'], description: '环境、社会、治理各维度指标数据' },
        { step: 3, action: '分析目标进展', models: ['ESGGoal'], description: '评估ESG目标达成情况' },
        { step: 4, action: '总结行动计划', models: ['ActionPlan'], description: '报告期内ESG举措和成效' },
        { step: 5, action: '发布ESG报告', models: ['FileInfo', 'ComplianceRecord'], description: '生成年度可持续发展报告' }
      ],
      keyQueries: [
        'SELECT framework, COUNT(*) as metric_count FROM ESGMetricDefinition GROUP BY framework',
        'SELECT dimension, AVG(achievement_rate) as avg_achievement FROM ESGGoalProgress GROUP BY dimension'
      ]
    }
  ];

  const toggleScenario = (id) => {
    setExpandedScenario(expandedScenario === id ? null : id);
  };

  return (
    <div className="w-full min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto">
        <h1 className="text-3xl font-bold text-center mb-4 text-gray-800">
          ESG业务场景数据模型应用
        </h1>
        <p className="text-center text-gray-600 mb-8 max-w-4xl mx-auto">
          基于核心数据模型，展示不同ESG业务场景的数据组织方式、处理流程和关键查询逻辑
        </p>
        
        <div className="grid gap-6">
          {scenarios.map((scenario) => (
            <div key={scenario.id} className="bg-white rounded-lg shadow-lg overflow-hidden">
              {/* 场景标题栏 */}
              <div 
                className="p-6 cursor-pointer transition-colors duration-200"
                style={{ backgroundColor: scenario.bgColor }}
                onClick={() => toggleScenario(scenario.id)}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-4">
                    <div 
                      className="p-3 rounded-lg"
                      style={{ backgroundColor: scenario.color, color: 'white' }}
                    >
                      {scenario.icon}
                    </div>
                    <div>
                      <h2 className="text-xl font-bold" style={{ color: scenario.color }}>
                        {scenario.title}
                      </h2>
                      <p className="text-gray-600 mt-1">{scenario.description}</p>
                      <div className="flex flex-wrap gap-2 mt-2">
                        {scenario.standards.map((standard, idx) => (
                          <span 
                            key={idx}
                            className="px-2 py-1 text-xs rounded-full bg-white border"
                            style={{ borderColor: scenario.color, color: scenario.color }}
                          >
                            {standard}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                  <div className="text-gray-400">
                    {expandedScenario === scenario.id ? <ChevronDown /> : <ChevronRight />}
                  </div>
                </div>
              </div>

              {/* 展开的详细内容 */}
              {expandedScenario === scenario.id && (
                <div className="p-6 border-t border-gray-200 bg-gray-50">
                  <div className="grid lg:grid-cols-2 gap-8">
                    
                    {/* 左侧：核心模型和数据流 */}
                    <div className="space-y-6">
                      
                      {/* 涉及的核心模型 */}
                      <div>
                        <h3 className="text-lg font-semibold mb-3 flex items-center">
                          <Database className="w-5 h-5 mr-2" style={{ color: scenario.color }} />
                          涉及的核心模型
                        </h3>
                        <div className="flex flex-wrap gap-2">
                          {scenario.coreModels.map((model, idx) => (
                            <span 
                              key={idx}
                              className="px-3 py-1 text-sm rounded-lg border font-medium"
                              style={{ 
                                backgroundColor: 'white',
                                borderColor: scenario.color,
                                color: scenario.color 
                              }}
                            >
                              {model}
                            </span>
                          ))}
                        </div>
                      </div>

                      {/* 业务流程 */}
                      <div>
                        <h3 className="text-lg font-semibold mb-3 flex items-center">
                          <GitBranch className="w-5 h-5 mr-2" style={{ color: scenario.color }} />
                          业务处理流程
                        </h3>
                        <div className="space-y-3">
                          {scenario.dataFlow.map((flow, idx) => (
                            <div key={idx} className="flex items-start space-x-3">
                              <div 
                                className="w-6 h-6 rounded-full flex items-center justify-center text-white text-sm font-bold flex-shrink-0"
                                style={{ backgroundColor: scenario.color }}
                              >
                                {flow.step}
                              </div>
                              <div className="flex-1">
                                <h4 className="font-medium text-gray-800">{flow.action}</h4>
                                <p className="text-sm text-gray-600 mt-1">{flow.description}</p>
                                <div className="flex flex-wrap gap-1 mt-2">
                                  {flow.models.map((model, modelIdx) => (
                                    <span 
                                      key={modelIdx}
                                      className="px-2 py-1 text-xs bg-gray-200 text-gray-700 rounded"
                                    >
                                      {model}
                                    </span>
                                  ))}
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>

                    {/* 右侧：关键查询和数据示例 */}
                    <div className="space-y-6">
                      
                      {/* 关键查询语句 */}
                      <div>
                        <h3 className="text-lg font-semibold mb-3 flex items-center">
                          <FileText className="w-5 h-5 mr-2" style={{ color: scenario.color }} />
                          关键查询逻辑
                        </h3>
                        <div className="space-y-3">
                          {scenario.keyQueries.map((query, idx) => (
                            <div key={idx} className="bg-gray-800 rounded-lg p-4">
                              <div className="flex items-center justify-between mb-2">
                                <span className="text-sm text-gray-400">查询 {idx + 1}</span>
                              </div>
                              <code className="text-sm text-green-400 block whitespace-pre-wrap">
                                {query}
                              </code>
                            </div>
                          ))}
                        </div>
                      </div>

                      {/* 输出成果 */}
                      <div>
                        <h3 className="text-lg font-semibold mb-3 flex items-center">
                          <Award className="w-5 h-5 mr-2" style={{ color: scenario.color }} />
                          预期输出成果
                        </h3>
                        <div className="bg-white rounded-lg p-4 border">
                          {scenario.id === 'pcf' && (
                            <div className="space-y-2">
                              <div className="font-medium">• 产品碳足迹报告 (PCF Report)</div>
                              <div className="font-medium">• 生命周期评估清单 (LCI Data)</div>
                              <div className="font-medium">• 碳足迹证书 (PCF Certificate)</div>
                              <div className="text-sm text-gray-600 mt-2">
                                符合ISO 14067标准，可用于产品碳标签、供应链披露、绿色采购等场景
                              </div>
                            </div>
                          )}
                          {scenario.id === 'inventory' && (
                            <div className="space-y-2">
                              <div className="font-medium">• 组织温室气体清单报告</div>
                              <div className="font-medium">• Scope1/2/3排放明细</div>
                              <div className="font-medium">• 第三方核查声明书</div>
                              <div className="text-sm text-gray-600 mt-2">
                                满足国家碳报告要求，支持碳交易、碳中和规划等业务需求
                              </div>
                            </div>
                          )}
                          {scenario.id === 'cbam' && (
                            <div className="space-y-2">
                              <div className="font-medium">• CBAM季度报告</div>
                              <div className="font-medium">• 产品隐含碳排放证书</div>
                              <div className="font-medium">• 碳价格支付凭证</div>
                              <div className="text-sm text-gray-600 mt-2">
                                确保欧盟出口合规，避免碳关税风险，维护贸易畅通
                              </div>
                            </div>
                          )}
                          {scenario.id === 'cdp' && (
                            <div className="space-y-2">
                              <div className="font-medium">• CDP气候变化问卷响应</div>
                              <div className="font-medium">• CDP评分报告 (A-D级)</div>
                              <div className="font-medium">• 气候风险管理计划</div>
                              <div className="text-sm text-gray-600 mt-2">
                                提升ESG评级，满足投资者和利益相关方期望，增强融资能力
                              </div>
                            </div>
                          )}
                          {scenario.id === 'ecovadis' && (
                            <div className="space-y-2">
                              <div className="font-medium">• EcoVadis可持续发展评估报告</div>
                              <div className="font-medium">• EcoVadis徽章认证 (铜/银/金/白金)</div>
                              <div className="font-medium">• 供应链ESG改进计划</div>
                              <div className="text-sm text-gray-600 mt-2">
                                获得国际客户认可，进入跨国公司供应链，提升品牌价值
                              </div>
                            </div>
                          )}
                          {scenario.id === 'esg_report' && (
                            <div className="space-y-2">
                              <div className="font-medium">• 年度可持续发展报告</div>
                              <div className="font-medium">• ESG关键绩效指标仪表板</div>
                              <div className="font-medium">• 利益相关方沟通材料</div>
                              <div className="text-sm text-gray-600 mt-2">
                                展示ESG成果，满足监管披露要求，提升企业社会责任形象
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>

        {/* 场景协同说明 */}
        <div className="mt-12 bg-white rounded-lg shadow-lg p-8">
          <h2 className="text-2xl font-bold mb-6 text-center text-gray-800">业务场景协同效应</h2>
          
          <div className="grid md:grid-cols-2 gap-8">
            <div>
              <h3 className="text-lg font-semibold mb-4 text-blue-600">数据复用优势</h3>
              <div className="space-y-3 text-gray-700">
                <div className="flex items-start space-x-3">
                  <div className="w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0"></div>
                  <div>
                    <strong>基础数据一次收集，多场景复用</strong>：Activity表中的活动数据可同时服务于PCF、碳盘查、CBAM等场景
                  </div>
                </div>
                <div className="flex items-start space-x-3">
                  <div className="w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0"></div>
                  <div>
                    <strong>排放因子统一管理</strong>：EmissionFactor表支持不同地理位置、时间、标准的因子，避免重复维护
                  </div>
                </div>
                <div className="flex items-start space-x-3">
                  <div className="w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0"></div>
                  <div>
                    <strong>组织架构共享</strong>：Organization和OperationalEntity为所有场景提供统一的组织视图
                  </div>
                </div>
              </div>
            </div>
            
            <div>
              <h3 className="text-lg font-semibold mb-4 text-green-600">业务场景互补</h3>
              <div className="space-y-3 text-gray-700">
                <div className="flex items-start space-x-3">
                  <div className="w-2 h-2 bg-green-500 rounded-full mt-2 flex-shrink-0"></div>
                  <div>
                    <strong>PCF为CBAM提供基础</strong>：产品碳足迹计算结果直接支撑CBAM合规申报
                  </div>
                </div>
                <div className="flex items-start space-x-3">
                  <div className="w-2 h-2 bg-green-500 rounded-full mt-2 flex-shrink-0"></div>
                  <div>
                    <strong>碳盘查支撑CDP评估</strong>：组织排放清单为CDP气候变化问卷提供数据基础
                  </div>
                </div>
                <div className="flex items-start space-x-3">
                  <div className="w-2 h-2 bg-green-500 rounded-full mt-2 flex-shrink-0"></div>
                  <div>
                    <strong>ESG目标统一管理</strong>：各认证和评估的目标在ESGGoal表中统一跟踪和管理
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div className="mt-8 p-6 bg-gradient-to-r from-blue-50 to-green-50 rounded-lg">
            <h3 className="text-lg font-semibold mb-3 text-gray-800">AI/ML增强能力</h3>
            <div className="grid md:grid-cols-3 gap-4 text-sm">
              <div className="bg-white p-4 rounded-lg shadow-sm">
                <h4 className="font-medium text-blue-600 mb-2">智能数据处理</h4>
                <p className="text-gray-600">自动识别活动类型、匹配排放因子、填补缺失数据，提升数据质量和处理效率</p>
              </div>
              <div className="bg-white p-4 rounded-lg shadow-sm">
                <h4 className="font-medium text-green-600 mb-2">预测性分析</h4>
                <p className="text-gray-600">基于历史数据预测未来排放趋势，识别减排机会，优化ESG目标设定</p>
              </div>
              <div className="bg-white p-4 rounded-lg shadow-sm">
                <h4 className="font-medium text-orange-600 mb-2">智能报告生成</h4>
                <p className="text-gray-600">根据不同标准和框架要求，自动生成符合格式的报告文档和披露材料</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}